<template>
  <view class="w-full">
    <!-- 申请用户列表 -->
    <view class="pt-[20rpx] pb-[32rpx] mt-10rpx">
      <view v-if="!registrationList.length" class="flex flex-col items-center justify-center py-[100rpx] bg-white rounded-[28rpx]">
        <view class="w-[160rpx] h-[160rpx] bg-gradient-to-br from-[#e3f2fd] to-[#bbdefb] rounded-full flex items-center justify-center mb-[30rpx]">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="dingdan" size="80" color="#2196F3" />
        </view>
        <view class="text-[30rpx] font-medium text-[#666]">暂无申请者</view>
      </view>

      <view class="flex flex-col gap-y-[20rpx]">
        <!-- 申请用户卡片 -->
        <view
          v-for="(applicant, index) in registrationList"
          :key="applicant.id"
          class="bg-white rounded-[24rpx] p-[24rpx] shadow-md relative"
          :class="isCurrentUserExecutor(applicant) ? 'border-2 border-red-500' : ''"
        >
          <!-- 状态标签 - 右上角 -->
          <view
            v-if="applicant.status == 10"
            class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#ffebee] text-[#f44336] border border-[#ffcdd2]"
          >
            ❌ 已拒绝
          </view>
          <view
            v-else-if="applicant.status == 11 || applicant.status > 20"
            class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#e8f5e9] text-[#4caf50] border border-[#c8e6c9]"
          >
            ✅ 已通过
          </view>
          <view v-else class="absolute top-[16rpx] right-[16rpx] px-[16rpx] py-[8rpx] rounded-[12rpx] text-[20rpx] font-medium bg-[#fff3e0] text-[#ff9800] border border-[#ffe0b2]"> ⏳ 待审核 </view>
          
          <!-- 用户基本信息 -->
          <view class="flex items-start justify-between mb-[20rpx]">
            <view class="flex items-center flex-1" @click="goToUserDetail(applicant)">
              <!-- 用户头像 -->
              <image :src="applicant.avatar_url || defaultAvatar" class="w-[80rpx] h-[80rpx] rounded-full mr-[16rpx] flex-shrink-0 user-avatar" mode="aspectFill" @error="handleAvatarError" />

              <view class="flex-1">
                <view class="flex items-center mb-[8rpx]">
                  <text class="text-[28rpx] font-bold text-[#333] mr-[12rpx]"> {{ applicant.name }} </text>
                </view>

                <!-- 用户标签 -->
                <view class="flex items-center gap-x-[8rpx] mb-[8rpx]">
                  <view v-for="tag in applicant.tags" :key="tag" class="px-[8rpx] py-[2rpx] bg-[#f5f5f5] text-[#666] text-[20rpx] rounded-[6rpx]">
                    {{ tag }}
                  </view>
                </view>

                <!-- 申请时间 -->
                <text class="text-[22rpx] text-[#999]"> 申请时间：{{ applicant.create_time }} </text>
              </view>
            </view>
          </view>

          <!-- 任务状态显示 -->
          <view class="stage-status flex items-center gap-[10rpx] mb-[16rpx]">
            <view class="text-[20rpx] text-[#999]">任务状态:</view>
            <text class="text-[20rpx]" :class="getStatusTextColor(applicant.status)">
              {{ getStatusLabel(applicant.status) }}
            </text>
            <template v-if="applicant.amount">
              <text class="text-[20rpx]" v-if="applicant.new_price && applicant.new_price != applicant.amount">
                <text class="text-[20rpx] text-[#999] line-through">¥{{ applicant.amount }}</text>
                <text class="text-[20rpx] text-[#ff0000]">￥{{ applicant.new_price }}</text>
              </text>
              <text class="text-[20rpx] text-[#ff0000]" v-else>￥{{ applicant.amount }}</text>
            </template>
          </view>

          <!-- 操作按钮 -->
          <view class="flex items-center gap-x-[12rpx]" v-if="!applicant.status && props.isPublisher">
            <nut-button size="small" type="default" class="flex-1" @click="handleContact(applicant)"> 立即联系 </nut-button>
            <nut-button v-if="!applicant.status" size="small" type="default" class="flex-1" @click="checkContact(applicant)"> 审核 </nut-button>
          </view>

          <!-- 功能按钮 - 根据状态和角色显示 -->
          <view class="flex items-center gap-x-[12rpx] mt-[16rpx]" v-if="applicant.status == 11 || applicant.status > 20">
            <!-- 发布者操作按钮 -->
            <template v-if="props.isPublisher">
              <nut-button
                v-for="(action, i) in getPublisherActions(applicant.status)"
                :key="i"
                size="small"
                type="primary"
                class="flex-1"
                @click="handlePublisherAction(applicant.id, index, action, applicant.status)"
              >
                {{ action }}
              </nut-button>
            </template>

            <!-- 执行者操作按钮 -->
            <template v-for="(action, i) in getExecutorActions(applicant.status)" :key="i">
              <nut-button size="small" type="default" class="flex-1" @click="handleExecutorAction(applicant.id, index, action, applicant.status)" v-if="isCurrentUserExecutor(applicant)">
                {{ action }}
              </nut-button>
            </template>
          </view>
        </view>
      </view>

      <view class="h-[120rpx]"></view>
    </view>

    <!-- 审核弹窗 -->
    <nut-overlay v-model:visible="auditModalVisible" z-index="3000">
      <view class="audit-modal flex items-center justify-center h-full">
        <view class="audit-content bg-white rounded-[24rpx] w-[600rpx] mx-[32rpx] p-[40rpx]">
          <!-- 弹窗头部 -->
          <view class="audit-header text-center mb-[32rpx]">
            <text class="text-[36rpx] font-bold text-[#333]">申请审核</text>
          </view>

          <!-- 用户信息 -->
          <view class="user-info flex items-center mb-[32rpx] p-[24rpx] bg-[#f8f9fa] rounded-[16rpx]">
            <image :src="currentAuditUser.avatar_url || defaultAvatar" class="w-[80rpx] h-[80rpx] rounded-full mr-[16rpx] flex-shrink-0 user-avatar" mode="aspectFill" @error="handleAvatarError" />
            <view class="user-details flex-1">
              <text class="block text-[28rpx] font-medium text-[#333] mb-[8rpx]">申请人：{{ currentAuditUser.name }}</text>
              <text class="text-[24rpx] text-[#666]">申请时间：{{ currentAuditUser.create_time }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="audit-actions flex gap-[16rpx]">
            <nut-button size="large" type="default" class="flex-1" @click="handleAuditCancel"> 取消 </nut-button>
            <nut-button size="large" type="danger" class="flex-1" :loading="auditLoading" @click="handleAuditApprove(0)"> 不通过 </nut-button>
            <nut-button size="large" type="success" class="flex-1" :loading="auditLoading" @click="handleAuditApprove(1)"> 通过 </nut-button>
          </view>
        </view>
      </view>
    </nut-overlay>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { post } from "@/utils/request";
import { getCurrentInstance } from "@tarojs/runtime";
import defaultAvatar from "@/assets/pic/ren.png";
import { StatusActions } from "@/constants/StatusActions";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";

const props = defineProps({
  tid: { type: String, default: "" },
  isPublisher: { type: Boolean, default: false },
  publisherId: { type: String, default: "" },
  totalAmount: { type: Number, default: 0 },
});

const emit = defineEmits(["list"]);

// 用户信息相关
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

// 申请用户列表
const registrationList = ref([]);

// 审核弹窗相关
const auditModalVisible = ref(false);
const currentAuditUser = ref({});
const auditLoading = ref(false);

/**
 * 获取发布者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getPublisherActions = (status) => {
  // 申请状态映射到任务状态
  const statusMapping = {
    11: "3", // 已通过 -> 待完成（发布者等待执行者提交）
  };

  // 如果状态在映射中，使用映射后的状态
  const mappedStatus = statusMapping[status] || status;
  console.log("mappedStatus=======", mappedStatus, status, StatusActions);
  return StatusActions[mappedStatus]?.publisherActions || [];
};

/**
 * 获取执行者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getExecutorActions = (status) => {
  // 申请状态映射到任务状态
  const statusMapping = {
    11: "0", // 已通过 -> 待完成（执行者可以提交"我已完成"）
  };

  // 如果状态在映射中，使用映射后的状态
  const mappedStatus = statusMapping[status] || status;
  console.log("mappedStatus=======", mappedStatus, status, StatusActions);
  return StatusActions[mappedStatus]?.executorActions || [];
};

/**
 * 判断当前用户是否为执行者
 * @param applicant 申请者信息
 * @returns 是否为执行者
 */
const isCurrentUserExecutor = (applicant) => {
  if (!userInfo.value || !applicant) return false;

  const currentUserId = userInfo.value.id;
  const applicantMemberId = applicant.member_id;

  console.log("当前用户ID:", currentUserId, "类型:", typeof currentUserId);
  console.log("申请者member_id:", applicantMemberId, "类型:", typeof applicantMemberId);

  // 转换为字符串进行比较
  const isExecutor = String(currentUserId) === String(applicantMemberId);
  console.log("是否为执行者:", isExecutor);

  return isExecutor;
};

/**
 * 获取状态标签文字
 * @param status 任务状态码
 * @returns 状态标签文字
 */
const getStatusLabel = (status) => {
  // 申请状态映射
  const applicationStatusMap = {
    10: "已拒绝",
    11: "待完成",
  };

  // 优先使用申请状态映射，然后使用 StatusActions
  return applicationStatusMap[status] || StatusActions[status]?.label || "未知状态";
};

/**
 * 获取状态文字颜色
 * @param status 任务状态码
 * @returns CSS类名
 */
const getStatusTextColor = (status) => {
  switch (status) {
    case 0:
      return "text-[#FF4D4F]"; // 待完成 - 红色
    case 3:
      return "text-[#52C41A]"; // 已完成 - 绿色
    case 21:
      return "text-[#FAAD14]"; // 待审核 - 橙色
    case 22:
      return "text-[#52C41A]"; // 确认完成 - 绿色
    case 23:
    case 24:
      return "text-[#FF4D4F]"; // 有纠纷/纠纷协商 - 红色
    case 10:
      return "text-[#FF4D4F]"; // 已拒绝 - 红色
    case 11:
      return "text-[#52C41A]"; // 已通过 - 绿色
    default:
      return "text-[#666666]"; // 默认灰色
  }
};

/**
 * 处理发布者操作
 * @param applicantId 申请者ID
 * @param index 索引
 * @param action 操作名称
 * @param currentStatus 当前状态
 */
const handlePublisherAction = async (applicantId, index, action, currentStatus) => {
  console.log("action==>", action);
  try {
    let newStatus = currentStatus;

    // 根据操作名称确定新状态
    switch (action) {
      case "联系执行者":
        // 跳到聊天页面
        const currentApplicant = registrationList.value[index];
        if (currentApplicant && currentApplicant.member_id) {
          Taro.navigateTo({
            url: `/pages/message/chat?userId=${currentApplicant.member_id}`,
          });
        } else {
          Taro.showToast({
            title: "获取执行者信息失败",
            icon: "error",
            duration: 2000,
          });
        }
        return;
      case "确认完成":
        // 调用确认完成接口
        const confirmRes = await Taro.showModal({
          title: "确认完成",
          content: "确定要确认完成吗？",
          confirmText: "确定",
          cancelText: "取消",
        });
        if (!confirmRes.confirm) return;
        newStatus = 22; // 确认完成
        break;
      case "有纠纷":
        // 显示纠纷弹窗
        const disputeRes = await Taro.showModal({
          title: "有纠纷",
          content: "确定要标记为有纠纷吗？",
          confirmText: "确定",
          cancelText: "取消",
        });
        if (!disputeRes.confirm) return;
        newStatus = 23; // 有纠纷
        break;
      case "联系平台":
        // 显示客服联系弹窗
        Taro.navigateTo({
          url: `/pages/webs/contact-us`,
        });
        return;
      default:
        Taro.showToast({
          title: "未知操作",
          icon: "error",
          duration: 2000,
        });
        return;
    }

    // 调用接口更新状态
    const res = await post("/check/updateSignUp", {
      id: applicantId,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      registrationList.value[index].status = newStatus;

      Taro.showToast({
        title: "操作成功",
        icon: "success",
        duration: 2000,
      });
    } else {
      Taro.showToast({
        title: res.data || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("发布者操作失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

/**
 * 处理执行者操作
 * @param applicantId 申请者ID
 * @param index 索引
 * @param action 操作名称
 * @param currentStatus 当前状态
 */
const handleExecutorAction = async (applicantId, index, action, currentStatus) => {
  try {
    let newStatus = currentStatus;

    // 根据操作名称确定新状态
    switch (action) {
      case "我已完成":
        newStatus = 21; // 待审核
        break;
      case "联系平台":
        // 显示客服联系弹窗
        Taro.navigateTo({
          url: `/pages/webs/contact-us`,
        });
        return;
      case "联系发布者":
        // 跳到聊天页面
        Taro.navigateTo({
            url: `/pages/message/chat?userId=${ props.publisherId }`,
          });
        return;
      case "接受方案":
        const acceptRes = await Taro.showModal({
          title: "接受方案",
          content: "确定要接受方案吗？",
          confirmText: "接受",
          cancelText: "取消",
        });
        if (!acceptRes.confirm) return;
        newStatus = 26; // 接受方案
        break;
      case "拒绝方案":
        const rejectRes = await Taro.showModal({
          title: "拒绝方案",
          content: "确定要拒绝方案吗？",
          confirmText: "拒绝",
          cancelText: "取消",
        });
        if (!rejectRes.confirm) return;
        newStatus = 25; // 拒绝方案
        break;
      default:
        Taro.showToast({
          title: "未知操作",
          icon: "error",
          duration: 2000,
        });
        return;
    }

    // 调用接口更新状态
    const res = await post("/check/updateSignUp", {
      id: applicantId,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      registrationList.value[index].status = newStatus;

      Taro.showToast({
        title: "操作成功",
        icon: "success",
        duration: 2000,
      });
    } else {
      Taro.showToast({
        title: res.data || "操作失败",
        icon: "error",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("执行者操作失败:", error);
    Taro.showToast({
      title: "网络错误，请重试",
      icon: "error",
      duration: 2000,
    });
  }
};

const handleContact = (item) => {
  // 跳转到聊天页面
  console.log("===>", item);
  Taro.navigateTo({
    url: `/pages/message/chat?userId=${item.member_id}&userName=${item.name}`,
  });
};

/**
 * 处理头像加载错误
 * @param {Event} event - 图片加载错误事件
 */
const handleAvatarError = (event) => {
  // 设置默认头像
  event.target.src = defaultAvatar;
};

/**
 * 审核申请用户
 * @param {Object} applicant - 申请用户信息
 */
const checkContact = (applicant) => {
  currentAuditUser.value = applicant;
  console.log("审核用户：", applicant);
  auditModalVisible.value = true;
};

/**
 * 审核
 */
const handleAuditApprove = async (n) => {
  if (auditLoading.value) return;

  auditLoading.value = true;

  try {
    let res = await post("/check/updateSignUp", {
      id: currentAuditUser.value.id,
      status: n == 0 ? 10 : 11,
    });
    if (res.code === 0) {
      // 关闭弹窗并刷新列表
      auditModalVisible.value = false;

      // 刷新申请列表
      if (props.tid) {
        getSignUpList(props.tid);
      }
    } else {
      Taro.showToast({
        title: res.data || "审核失败",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("审核不通过失败：", error);
    Taro.showToast({
      title: "网络异常，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    auditLoading.value = false;
  }
};

/**
 * 取消审核
 */
const handleAuditCancel = () => {
  auditModalVisible.value = false;
  currentAuditUser.value = {};
};

/**
 * 跳转到用户详情页
 * @param {Object} applicant - 申请用户信息
 */
function goToUserDetail(applicant) {
  if (!applicant.member_id) return;
  Taro.navigateTo({
    url: `/pages/mine/other?id=${applicant.member_id}`,
  });
}

// 申请用户列表
const getSignUpList = async (id) => {
  const res = await post("/check/signUpList", {
    // id: id,
    taskId: id,
  });
  if (res.code == 0) {
    registrationList.value = res.data.map((item) => ({
      ...item.columns,
    }));
    console.log("申请用户列表==>", res.data);
    emit("list", res.data);
  }
};

// 页面加载时获取数据
onMounted(() => {
  if (props.tid) {
    getSignUpList(props.tid);
  }
});
</script>

<style lang="scss">
// 头像样式优化
.user-avatar {
  border: 2rpx solid #e5e7eb;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

// 确保头像在加载失败时有合适的显示
image {
  background-color: #f3f4f6;
}
</style>
